import router from './index.js'
import { message } from 'ant-design-vue'
import useUserStore from '@/stores/user'
import dayjs from 'dayjs'

router.beforeEach((to, from, next) => {
  try {
    // if (to.path !== '/expiration' && dayjs().isAfter(dayjs(expirationDate), 'day')) {
    //   next('/expiration')
    // }
    const userStore = useUserStore()
    let token = userStore.token
    if (to.meta.hasLogin === false) {
      next()
    } else if (token) {
      /* has token*/
      if (to.path === '/login') {
        next({ path: '/home' })
      } else {
        if (userStore.userInfo && userStore.userInfo.id) {
          if (!userStore.menuList || userStore.menuList.length === 0) {
            userStore.getProjectAll().then(() => {
              next()
            })
          } else {
            next()
          }
        } else {
          let timer = null
          let time = 0
          timer = setInterval(async () => {
            time++
            if (
              window.frames['test'] &&
              window.frames['test'].document.querySelector('h1') &&
              window.frames['test'].document.querySelector('h1').innerHTML === 'Security Enhance'
            ) {
              clearInterval(timer)
              let userInfoRes = await userStore.getUserInfo()
              if (userInfoRes) {
                // 这时候去获取所有项目并根据项目区生成菜单
                await userStore.getProjectAll()
                next() // hack方法 确保addRoutes已完成
              } else {
                userStore.doLogout().then(() => {
                  next({
                    path: `/login?redirect=${document.URL.substring(document.URL.indexOf('#'))}`
                  })
                })
              }
            } else if (time > 30) {
              clearInterval(timer)
            }
          }, 100)
        }
      }
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  } catch (e) {
    console.log('beforeEach err', e)
  }
})

router.afterEach(() => {})
